import java.util.Arrays;

/**
 * 堆的时间复杂度实际是O(n)
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/10/11 10:10
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    /**
     * 向下转型的实现
     * @param parent
     * @param len
     */
    public void shiftDown(int parent,int len){
        int child = 2*parent+1;
        while(child<len){
            if(child+1 < len && elem[child] < elem[parent]){
                child++;
            }
            if(elem[child]>elem[parent]){
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                child = parent;
                child = 2*parent+1;
            }else{
                break;
            }
        }
    }


    public void createHeap(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            this.usedSize++;
        }
        for (int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            //调整
            shiftDown(parent,usedSize);

        }
    }

    public void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while (child > 0) {
            if (elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            }else{
                break;
            }
        }
    }

    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize++] = val;
        shiftUp(usedSize-1);
    }

    public boolean isFull(){
        return usedSize == elem.length;
    }

    public int poll(){
        if(isEmpty()) {
            throw new RuntimeException("null");
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        shiftDown(0,usedSize);
        return tmp;
    }

    public boolean isEmpty(){
        return usedSize == 0;
    }

    /**
     * 堆排序
     * 从小到大
     */
    public void heapSort() {
        int end = usedSize - 1;
        while (end != 0) {
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = tmp;
            shiftDown(0, end);
            end--;
        }
    }

}
